package net.hzfanqun.nutz.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

@IocBean
@Ok("json")
public class HelloWorld {

	@At("/yousay")
	@Ok("jsp:/newjsp") // 返回形式是jsp
	public String tellMore(HttpServletRequest request, ServletContext context, @Param("username") String username,
			@Param("age") String age, HttpSession session) throws IOException {

		// 从request中取得输入流
		InputStream inputStream = request.getInputStream();	//因为通过@Param已经读过了，所以这次返回null
		BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
		
		// 每次读取的内容
		String line = null;
		// 最终读取的内容
		StringBuffer buffer = new StringBuffer();
		
		while((line = br.readLine()) != null){
			buffer.append(line);
		}
		// 释放资源
		inputStream.close();
		inputStream = null;
		br.close();
		br = null;

		System.out.println("buffer: " + buffer);
		request.setAttribute("username_age", username + "_" + age);
		// 测试出错后能否转到error.jsp
		// int i = Integer.parseInt("bcd");
		String str = "{'username':'" + username + "','age':'" + age + "','append':'nutzAppend'}";
		return str;
	}
	
	@At("/comp")
	@Ok("jsp:/comp")
	public String comp(){
		return "success";
	}
	
	@At("/compret")
	@Ok("jsp:/comp") // 返回形式是jsp
	public String comp(HttpServletRequest request, ServletContext context, @Param("errorid") String errorid,
			HttpSession session) throws IOException {
		request.setAttribute("errorid", errorid);
		if (errorid == null || errorid.isEmpty())
			return "Input is empty.";

		long result,origin= Long.valueOf(errorid);
		result = origin & 0x00000000FFFFFFFFL;
		
		System.out.println("WORD: " + result);
		String str = "{'error_id':'" + errorid + "','origin_id':'" + result + "','append':'iegreen'}";
		Integer i;
		i= (int)result;
		
		System.out.println("Integer: " + i);

		return str;
	}

}
